package com.tjsinfo.tjsoa.common;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import com.tjsinfo.tjsoa.system.vo.Files;
import com.tjsinfo.tjsoa.system.vo.TBuploadFiles;

public class DealString {
	/**
     * @param 传入request,
     * @return 当前项目路径 
     * 
     */
	public static String getProjectPath(HttpServletRequest request){
		return request.getSession().getServletContext().getRealPath( "/");
	}
	/**
     * @param 传入request,
     * @param fromFile,源文件目录 
     * @param toFile,目标文件目录
     * @return 返回保存的文件
     *  
     */
	public static List<TBuploadFiles> copyFileGetUploadVo(HttpServletRequest request,String fromFile,String toFile){
		Enumeration<String> enums=request.getParameterNames();
		List<TBuploadFiles> fileList=new ArrayList<TBuploadFiles>();
		
		while (enums.hasMoreElements()) {
			String elem = (String) enums.nextElement();
			if(elem.length()>10){
				if("fiid".equals(elem.substring(0, 4))){
					//返回保存文件目录 
					TBuploadFiles file=new TBuploadFiles();
					file.setFcfileName(request.getParameter(elem));
					file.setFrfileName(request.getParameter(elem.replace("fiid", "fiNa")));
					System.out.println(toFile+request.getParameter(elem));
					fileList.add(file);
					//文件复制过程
					File rfile=new File(fromFile+request.getParameter(elem));
					FileManage.moveFile(fromFile+request.getParameter(elem), toFile+request.getParameter(elem));
				}
			}
		}
		
		return fileList;
	}
	/**
     * @param 传入request,
     * @param fromFile,源文件目录
     * @param toFile,目标文件目录
     * @return 返回保存的文件
     * 
     */
	public static List<Files> fileCopyTofile(HttpServletRequest request,String fromFile,String toFile){
		Enumeration<String> enums=request.getParameterNames();
		List<Files> fileList=new ArrayList<Files>();
		
		while (enums.hasMoreElements()) {
			String elem = (String) enums.nextElement();
			if(elem.length()>10){
				if("fiid".equals(elem.substring(0, 4))){
					//返回保存文件目录 
					Files file=new Files();
					
					file.setNewFileName(request.getParameter(elem));
					file.setOldFileName(request.getParameter(elem.replace("fiid", "fiNa")));
					//加入FileSize
					file.setFileSize(request.getParameter(elem.replace("fiid", "fiSize")));
					file.setToFilePath(toFile+request.getParameter(elem));
					fileList.add(file);
					//文件复制过程
					File rfile=new File(fromFile+request.getParameter(elem));
					FileManage.moveFile(fromFile+request.getParameter(elem), toFile+request.getParameter(elem));
				}
			}
		}
		
		return fileList;
	}
	/**
     * @param h
     * @return
     * 实现对map按照value升序排序
     */
    @SuppressWarnings("unchecked")
    public static String getErrorMessage(Exception e) {
        StringBuffer sb=new StringBuffer();
		StackTraceElement[] ste=e.getStackTrace();
		for (StackTraceElement stackTraceElement : ste) {
			sb.append(stackTraceElement.getFileName());
			sb.append("中");
			sb.append(stackTraceElement.getMethodName());
			sb.append("方法异常,源于line:");
			sb.append(stackTraceElement.getLineNumber());
			sb.append("<br/>");
		}
        return sb.toString();
    }
	
	/**
     * @param h
     * @return
     * 实现对map按照value升序排序
     */
    @SuppressWarnings("unchecked")
    public static Map.Entry[] getSortedHashtableByValue(Map h) {
        Set set = h.entrySet();
        Map.Entry[] entries = (Map.Entry[]) set.toArray(new Map.Entry[set
                .size()]);
        Arrays.sort(entries, new Comparator() {
            public int compare(Object arg0, Object arg1) {
                Long key1 = Long.valueOf(((Map.Entry) arg0).getValue().toString());
                Long key2 = Long.valueOf(((Map.Entry) arg1).getValue().toString());
                return key1.compareTo(key2);
            }
        });

        return entries;
    }

 

 

    /**
     * @param h
     * @return
     * 实现对map按照key排序
     */
    @SuppressWarnings("unchecked")
    public static Map.Entry[] getSortedHashtableByKey(Map h) {

        Set set = h.entrySet();

        Map.Entry[] entries = (Map.Entry[]) set.toArray(new Map.Entry[set
                .size()]);

        Arrays.sort(entries, new Comparator() {
            public int compare(Object arg0, Object arg1) {
                Object key1 = ((Map.Entry) arg0).getKey();
                Object key2 = ((Map.Entry) arg1).getKey();
                return ((Comparable) key1).compareTo(key2);
            }

        });

        return entries;
    }


	
	public static String convertTotalSize(int total_size)
	{
		String ret = "";
		String temp,temp1,temp2,temp3;
		int j, k, len;

		len = String.valueOf(total_size).length();
		
		//单位为（B）
		if (len < 4)
		{
			ret = String.valueOf(total_size) + "(B)";
		}
		//单位为（K）
		if (len >= 4 && len < 7)
		{
			temp = String.valueOf(total_size / 1000);
			ret = temp + "(K)";
		}
		//单位为（M）
		if (len >= 7)
		{
			temp = String.valueOf(total_size / 1000000);
			ret = temp + "(M)" ;
		}
		
		return ret; 
	}
	
	//将 日期==>字符串[转换成]
	public String dateToString(java.util.Date date) {
		java.text.SimpleDateFormat sdf=new java.text.SimpleDateFormat("yyyyMMddHHmm");
		String bianhao=sdf.format(date);
		return bianhao;
	}

	/*
	 * j为要截取的串 i为截取的个数
	 * 实现截取字符串功能
	 */ 
	public String SubStr(String j, int i) {
		String j1 = j;
		int i1 = i;
		if (j1.length() > i1) {
			j1 = j1.substring(0, i1);
			j1=j1+"...";
			return j1;
		} else {
			return j1;
		}

	}
	/*
	 * 获得新添加的字符串
	 */ 
	public static String addRoleString(String oldStr,String newStr) {
		String[] temp=oldStr.split(",");
	    for(int i=1;i<temp.length;i++){
	    	newStr=newStr.replace(","+temp[i]+",", ",");
	    }
	    return newStr;
	}
	/*
	 * 去掉的字符串
	 */ 
	public static String removeRoleString(String oldStr,String newStr) {
		String[] temp=newStr.split(",");
	    for(int i=1;i<temp.length;i++){
	    	oldStr=oldStr.replace(","+temp[i]+",", ",");
	    }
	    return oldStr;
	}
	
	/*
	 * ids为要去除重复的字符串
	 * 实现截取字符串功能
	 */ 
	public static String noAgain(String ids) {
		String[] temp=ids.split(",");
	    String idsNew=",";
	    for(int i=1;i<temp.length;i++){
	    	if(!idsNew.contains(","+temp[i]+","))idsNew=idsNew+temp[i]+",";
	    }
	    return idsNew;
	}
	public static String noAgain(String oldStr,String tempStr) {
		String[] temp=tempStr.split(",");
	    for(int i=1;i<temp.length;i++){
	    	if(oldStr.contains(","+temp[i]+","))oldStr=oldStr.replace(","+temp[i]+",", ",");
	    }
	    return oldStr;
	}
	
	/*
	 * 两个字符串去除相同项
	 * oldStr yuan
	 * 实现截取字符串功能
	 */ 
	public static String twoNoAgain(String oldStr,String tempStr) {
		String[] temp=tempStr.split(",");
	    for(int i=1;i<temp.length;i++){
	    	if(!oldStr.contains(","+temp[i]+","))oldStr=oldStr+temp[i]+",";
	    }
	    return oldStr;
	}
	public String substring(String j, int i) {
		String j1 = j;
		int i1 = i;
		if (j1.length() > i1) {
			j1 = j1.substring(0, i1); 
			return j1;
		} else {
			return j1;
		}

	}
	/*
	 * pic 字段为文章对应图片，bakPic为备用图片，当文章没有图片时可以显示
	 * 备用图片
	 */
	public String JudgePic(String pic,String bakPic){
		if(pic.length()==0||pic.equals("")){			
			return bakPic;				
		}else{
			return pic;
		}
	}
	/*
	 * 格式化日期
	 */
	public String FormatDate(Date date ){
		SimpleDateFormat a=new SimpleDateFormat("yyyy-MM-dd");
		String dateF=a.format(date);
		return dateF;
	}
	/*
	 * 格式化日期
	 */
	public String formatDate(Date date ){
		SimpleDateFormat a=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateF=a.format(date);
		return dateF;
	}
	/*
	 * 处理图片为合适大小,pic 为原图片字段，height为需要处理的图片的高，width为需要处理的宽
	 */
	public String ReworkPic(String pic,int height,int width){
			if(pic==null||pic.equals("")||!pic.startsWith("<img")){
				return "暂无照片";
			}else{
				String src=	GetSrc(pic);	
				StringBuffer s=new StringBuffer("<img height=\"");
				s.append(height);
				s.append("\" width=\"");
				s.append(width);
				s.append("\" alt=\"\" src=\"");
				s.append(src);
				s.append("\" border=\"0\" />");	
				String p=s.toString();
				
				return p; 
		}
	}
	/*
	 * 取得文件名
	 */
	public String GetSrc(String pic){	
		int i0=0;		
		int j0=0;
		i0=pic.lastIndexOf('"');
		j0=pic.indexOf("src=\"");
		j0=j0+5;
		String src=pic.substring(j0,i0);
		
		return src;
	}
	/*
	 * 上传文件中取得文件名
	 */
	public String GetPathName(String path){
		int last=path.lastIndexOf("/");
		int leng=path.length();
		String name=path.substring(last,leng);		
		return name;
	}
	/*
	 * 上传文件中取得文件名(不带/的)
	 */
	public String GetPathName1(String path){
		int last=path.lastIndexOf("/")+1;
		int leng=path.length();
		String name=path.substring(last,leng);		
		return name;
	}
	/*
	 * 上传文件中取得文件名(不带/的)
	 */
	public String GetPath(String path){
		int last=path.lastIndexOf("/");
		//int leng=path.length();
		String name=path.substring(0,last);		
		return name;
	} 
	public String toUtf8(String oldStr){
		if(oldStr==null||oldStr.equals("")){
			return "";			
		}
		//编码方式的转换
		String newStr = null;
		try {
			newStr=new String(oldStr.getBytes("ISO-8859-1"),"UTF-8");
		} catch (UnsupportedEncodingException e) {			
			e.printStackTrace();
		} 	
		return newStr;
	}
	/**
     * 取字符串的前toCount个字符
     *
     * @param str 被处理字符串
     * @param toCount 截取长度
     * @param more 后缀字符串
     * @version 2004.11.24
     * @author zhulx
     * @return String
     */
    public String subchar(String str, int toCount,String more)
    {
      int reInt = 0;
      String reStr = "";
      if (str == null)
        return "";
      char[] tempChar = str.toCharArray();
      for (int kk = 0; (kk < tempChar.length && toCount > reInt); kk++) {
        String s1 = str.valueOf(tempChar[kk]);
        byte[] b = s1.getBytes();
        reInt += b.length;
        reStr += tempChar[kk];
      }
      if (toCount == reInt || (toCount == reInt - 1))
        reStr += more;
      return reStr;
    }
    //将传入的字符串转换成 数组形式
    public String[] getSeparate(String separate,String arg0){
    	String result[]=null;
    	try{    		
    		if("+".equals(arg0)||"*".equals(arg0)||"|".equals(arg0)||"\\".equals(arg0)){
    			result= separate.split("["+arg0+"]");
    		}else{
    			result= separate.split(arg0);
    		} 	
        	
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	return result;
    	
    }
    //将字符串＝＝》转化成 日期型数据
    //2007-08-15 00:00:00
    public Date strToDate(String strDate){
    	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	Date resultDate=new Date();
    	try {
			resultDate = sdf.parse(strDate); 
		} catch (ParseException e) {
			
			e.printStackTrace();
		}    	
		
    	return resultDate;
    }
    //将字符串 2007-9-10 17:29:09 转化成 07-09
    public String yearMonth(String strDate){
    	StringBuffer sbf=new StringBuffer();
    	String year=strDate.substring(2, 4);
    	String month;
    	if(strDate.lastIndexOf("-")==6){
    		month=strDate.substring(5,6);
    		month="0"+month;
    	}else{
    		month=strDate.substring(5,7);
    	}
    	
    	System.out.println("month="+month);
    	sbf.append(year);
    	sbf.append("-");
    	sbf.append(month);
    
    	return sbf.toString();
    } 
    //将字符串 2007-9-10 17:29:09 转化成 07-09-10
    //2007-09-10
    public String yearMonthDay(String strDate){
    	int flag=strDate.indexOf(":");
    	if(flag==-1){
    		return strDate.substring(2,10);
    	}
    	return strDate.substring(2,flag-3);
    }
    //将字符串 2007-9-10 17:29:09 转化成 2007-9-10
    public String year4MonthDay(String strDate){
    	int flag=strDate.indexOf(":");
    	if(flag==-1){
    		return strDate;    		
    	}
    	return strDate.substring(0,flag-3);
    	
    	
    }
	public String md5(){
		Random rnm = new Random();
		char a = (char) ((int) (rnm.nextDouble() * 26 + 97));
		char b = (char) ((int) (rnm.nextDouble() * 26 + 97));
		return String.valueOf(a)+String.valueOf(b);
	}
    public String Md5(String plainText) {
		StringBuffer buf = new StringBuffer("");
		String str=md5();
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			plainText=str+plainText;
			md.update(plainText.getBytes());
			byte b[] = md.digest();
			int i;
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return str+buf.toString().toUpperCase();
	}
    
    public void Upload(String path){
    	LinkedList list = new LinkedList();
		File dir = new File("d:\\project\\电子版规范\\");
		File file[] = dir.listFiles();
		for (int i = 0; i < file.length; i++) {
			if (file[i].isDirectory())
				list.add(file[i]);
			else
			{
				;
			}
				
		}
		File tmp;
		while (!list.isEmpty()) {
			tmp = (File) list.removeFirst();
			if (tmp.isDirectory()) {
				file = tmp.listFiles();
				if (file == null)
					continue;
				for (int i = 0; i < file.length; i++) {
					if (file[i].isDirectory())
						list.add(file[i]);
					else
					{
						;
					}
						
				}
			} else {
				
			}
		}
    }
}
